<?php

namespace app\api\controller;

use think\Image;

class UploadFile extends Basic
{

    protected $user = [];
    protected $userid = 0;
    protected $table;

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $info = $this->getUserInfoByToken();

        if (!empty($info)) {
            if ($info['table'] == 'member') {
                $where = ['memberid' => $info['userid']];
                $table = 'member';
            } else {
                $where = ['coachid' => $info['userid']];
                $table = 'coach';
            }
            $res = $this->findTable($table, ['where' => $where]);

            $this->userid = $info['userid'];
            $this->user = $res;
            $this->table = $table;
        } else {
            return $this->json([], 999, '登录超时，请重新登录');
        }

        $file = request()->file('file');
        $type = input('type');
        if (empty($type) || !in_array($type, ['avatar', 'view', 'certificate', 'qrcode'])) {
            return $this->json(null, 2000, '类型参数错误');
        }
        try {
            $result = $this->handleUploadFile($file, [
                'rule' => [
                    'mimeType' => 'jpg,png,JPG,JPEG,PNG,jpeg',
                    'size' => '200',
                    'image' => '5000,5000',
                    'suffix' => 'jpg,png'
                ],
                'msg' => [
                    'mimeType' => '图片格式错误',
                    'size' => '图片大小超过200MB',
                    'image' => '图片尺寸不符合规范',
                    'suffix' => '图片后缀错误'
                ]
            ], $type);
            $url = '';
            if (!empty($result['data'])) {
                $url = \think\facade\Request::domain(true) . '/public' . $result['data'];
            }
            return $this->json($url, $result['code'], $result['msg']);
        } catch (\think\Exception $e) {
            return $this->json(null, 2000, $e->getMessage());
        }
    }

    /**
     * 检查上传文件的合法性
     *
     * @param $file
     * @param $rule
     * @return array
     */
    public function handleCheck($file, $rule)
    {
        $rule_d = $rule['rule'];
        foreach ($rule_d as $key => $val) {
            switch ($key) {
                case 'suffix':
                    $nameArr = explode('.', $file->getOriginalName());
                    $name = $nameArr[count($nameArr) - 1];
                    if (strpos($val, $name) !== false) {
                    } else {
                        return ['states' => false, 'msg' => $rule['msg'][$key]];
                    }
                    break;
                case 'mimeType':
                    $type = explode('/', $file->getMime())[1];
                    if (strpos($val, $type) !== false) {
                    } else {
                        return ['states' => false, 'msg' => $rule['msg'][$key]];
                    }
                    break;
                case 'size':
                    $size = (int) $file->getSize() / 1024000;
                    if ($size > $val) {
                        return ['states' => false, 'msg' => $rule['msg'][$key]];
                    }
                    break;
                case 'image':
                    $image = Image::open($file->getRealPath());
                    $width = $image->width();
                    $height = $image->height();
                    $image = explode(',', $val);
                    if ($width > $image[0] || $height > $image[1]) {
                        return ['states' => false, 'msg' => $rule['msg'][$key]];
                    }
                    break;
                default:
                    $pice_path = '/runtime/storage/other/';
                    break;
            }
        }
        return ['states' => true, 'msg' => '效验正常'];
    }

    /**
     * 按照类别上传文件到指定的目录
     *
     * @param $file
     * @param null $rule
     * @param $type
     * @return array
     * @throws \think\Exception
     */
    public function handleUploadFile($file, $rule = null, $type)
    {
        $base_path = '.';
        switch ($type) {
            case 'view':
                $pice_path = '/static/uploads/image/' . $this->table . '/' . $this->userid . '/';
                break;
            case 'avatar':
                $pice_path = '/static/uploads/avatar/' . $this->table . '/' . $this->userid . '/';
                break;
            case 'certificate':
                $pice_path = '/static/uploads/certificate/' . $this->table . '/' . $this->userid . '/';
                break;
            case 'qrcode':
                $pice_path = '/static/uploads/qrcode/' . $this->table . '/' . $this->userid . '/';
                break;
            case 'image':
                $pice_path = '/storage/image/' . $this->table . '/' . $this->userid . '/' . date('Ymd') . '/';
                break;
            case 'zip':
                $pice_path = '/storage/zip/' . $this->table . '/' . $this->userid . '/' . date('Ymd') . '/';
                break;
            case 'video':
                $pice_path = '/storage/video/' . $this->table . '/' . $this->userid . '/' . date('Ymd') . '/';
                break;
            case 'word':
                $pice_path = '/storage/word/' . $this->table . '/' . $this->userid . '/' . date('Ymd') . '/';
                break;
            default:
                $pice_path = '/storage/other/' . $this->table . '/' . $this->userid . '/' . date('Ymd') . '/';
                break;
        }

        if ($rule == null) {
            $status = ['states' => true, 'msg' => '无需效验'];
        } else {
            $status = $this->handleCheck($file, $rule);
        }

        if ($status['states'] == true) {
            $type = explode('/', $file->getMime())[1];
            $image_name = md5(date('Ymd-His') . mt_rand(1, 99999)) . "." . $type;
            if (!file_exists($base_path . $pice_path)) {
                mkdir($base_path . $pice_path, 0777, true);
            }
            $image_file_path = $pice_path;
            $image_file = $base_path . $image_file_path;
            $imge_real_url = $image_file . '/' . $image_name;
            $imge_web_url = $image_file_path . '/' . $image_name;
            if (!file_exists($image_file)) {
                mkdir($image_file, 0777, true);
                // fopen($image_file . '/' . $image_name, "w");
            }
            $real_path = $file->getRealPath();
            if (move_uploaded_file($real_path, $imge_real_url)) {
                return ['code' => 1000, 'data' => $imge_web_url, 'msg' => '文件上传成功'];
            } else {
                return ['code' => 2000, 'data' => null, 'msg' => '文件上传失败'];
            }
        } else {
            throw new \think\Exception($status['msg']);
        }
    }
}
